// 分页列表
import API from '../api/request'

export default class Page {
	constructor(props) {
		const { apiUrl, page, data, dataKey, params, httpMethod } = props
		this.apiUrl = apiUrl
		this.page = page || 1
		this.data = data || []
		this.dataKey = dataKey || 'data'
		this.params = params || {}
		this.isLoaded = false
		this.isEmpty = false
		this.httpMethod = httpMethod || 'post'
		if (!this.apiUrl) {
			console.log('apiUrl不能为空')
		}
	}

	async _onFetch() {
		if (this.isEmpty || this.isLoaded) return
		let res = await API[this.httpMethod](this.apiUrl, {
			...this.params,
			page: this.page
		})
		let data
		if (res.code === '200') {
			data = this._getData(res)
			let pageInfo = this._getData(res, true)
			if (this.page === 1) {
				this.data = data
			} else {
				this.data = [...this.data, ...data]
			}
			if (!data.length || !pageInfo.hasNextPage) {
				this.isLoaded = true
			}
			if (!this.data.length) {
				this.isEmpty = true
			}
		}
		return this.data
	}

	_getData(res, isPage) {
		let keys = this.dataKey.split('.') || []
		isPage && keys.pop()

		for (let i = 0, len = keys.length; i < len; i++) {
			if (res[keys[i]]) {
				res = res[keys[i]]
			} else {
				res = []
				break
			}
		}
		return res
	}

	setAttr(key, val) {
		this[key] = val
		return this
	}

	async start() {
		this.page = 1
		this.isLoaded = false
		this.data = []
		return await this._onFetch()
	}

	async next() {
		this.page++
		return await this._onFetch()
	}
}
